<template>
  <div v-loading="loading" element-loading-text="大模型自动标引中" class="app-container" style=" min-height:550px ">
    <div class="filter-container">
      <div class="page-header-wrapper">
        <div class="header-status-section">
          <div v-if="z_status == 0" class="status-indicator status-pending">
            <i class="el-icon-warning-outline" />
            <span>待审核</span>
            <div class="status-description">
              以下内容为自动标引推荐，可手动校正，审核无误后点右上角按钮提交。
            </div>
          </div>
          <div v-if="z_status == 1" class="status-indicator status-approved">
            <i class="el-icon-circle-check" />
            <span>已审核</span>
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="submit(1)">
              审核并下一篇
            </el-button>
            <el-button @click="submit(2)">
              保存并返回
            </el-button>
          </div>
        </div>
        <el-divider />
      </div>
      <div class="main-content-wrapper">
        <div class="form-section">
          <el-form ref="dataForm" :model="form" label-width="80px" :rules="rules">
            <div class="form-row">
              <el-form-item label="档号" class="form-item">
                <el-input v-model="form.dh.value" size="mini" @input="handleInputChange('dh')" />
              </el-form-item>

              <el-form-item label="主题词" class="form-item">
                <el-input v-model="form.ztc.value" size="mini" @input="handleInputChange('ztc')" />
              </el-form-item>
            </div>
            <div class="form-row">
              <el-form-item label="密级" class="form-item">
                <el-input v-model="form.mj.value" size="mini" @input="handleInputChange('mj')" />
              </el-form-item>

              <el-form-item label="保管期限" class="form-item">
                <el-input v-model="form.bgqx.value" size="mini" @input="handleInputChange('bgqx')" />
              </el-form-item>
            </div>
            <div class="form-row">
              <el-form-item label="全宗号" class="form-item">
                <el-input v-model="form.qzh.value" size="mini" />
              </el-form-item>

              <el-form-item label="分类号" class="form-item">
                <el-input v-model="form.flh.value" size="mini" />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="案卷号" class="form-item">
                <el-input v-model="form.ajh.value" size="mini" @input="handleInputChange('ajh')" />
              </el-form-item>

              <el-form-item label="件号" class="form-item">
                <el-input v-model="form.jh.value" size="mini" @input="handleInputChange('jh')" />
              </el-form-item>
            </div>
            <div class="form-row">
              <el-form-item label="附注" class="form-item">
                <el-input v-model="form.fz.value" size="mini" @input="handleInputChange('fz')" />
              </el-form-item>

              <el-form-item label="类别号" class="form-item">
                <el-input v-model="form.lbh.value" size="mini" @input="handleInputChange('lbh')" />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="文种" class="form-item">
                <el-input v-model="form.wz.value" size="mini" @input="handleInputChange('wz')" />
              </el-form-item>

              <el-form-item label="时间" class="form-item">
                <el-input v-model="form.sj.value" size="mini" @input="handleInputChange('sj')" />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="题名" class="form-item">
                <el-input v-model="form.tm.value" size="mini" @input="handleInputChange('tm')" />
              </el-form-item>

              <el-form-item label="文件编号" class="form-item">
                <el-input v-model="form.wjbh.value" size="mini" @input="handleInputChange('wjbh')" />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="责任者" class="form-item">
                <el-input v-model="form.zrz.value" size="mini" @input="handleInputChange('zrz')" />
              </el-form-item>

              <el-form-item label="缩微号" class="form-item">
                <el-input v-model="form.swh.value" size="mini" @input="handleInputChange('swh')" />
              </el-form-item>
            </div>
            <div class="form-row">
              <el-form-item label="档案馆代号" class="form-item">
                <el-input v-model="form.dagdh.value" size="mini" @input="handleInputChange('dagdh')" />
              </el-form-item>

              <el-form-item label="数据类型" class="form-item">
                <el-input v-model="form.sjlx.value" size="mini" @input="handleInputChange('sjlx')" />
              </el-form-item>
            </div>
            <div class="form-row">
              <el-form-item label="载体类型" class="form-item">
                <el-input v-model="form.ztlx.value" size="mini" @input="handleInputChange('ztlx')" />
              </el-form-item>

              <el-form-item label="载体数量" class="form-item">
                <el-input v-model="form.ztsl.value" size="mini" @input="handleInputChange('ztsl')" />
              </el-form-item>
            </div>
            <div class="form-row">
              <el-form-item label="载体单位" class="form-item">
                <el-input v-model="form.ztdw.value" size="mini" @input="handleInputChange('ztdw')" />
              </el-form-item>

              <el-form-item label="载体规格" class="form-item">
                <el-input v-model="form.ztgg.value" size="mini" @input="handleInputChange('ztgg')" />
              </el-form-item>
            </div>
          </el-form>
        </div>

        <div class="content-section">
          <div class="content-tabs-wrapper">
            <el-tabs v-model="activeName" size="mini" class="custom-tabs">
              <el-tab-pane label="文档" name="文档" />
              <el-tab-pane v-if="form.gzmc.value" label="公章识别" name="公章识别" />
              <el-tab-pane v-if="form.mdArr && form.mdArr.key1" label="表单识别" name="表单识别" />
            
            </el-tabs>

            <div class="tab-content-wrapper">
              <div v-if="activeName == '文档'">
                <div class="document-image-viewer">
                  <div v-if="form && form.image_path && form.image_path.length > 0" class="image-container">
                    <div class="image-navigation">
                      <i class="el-icon-picture-outline"></i>
                      <span>共找到 {{ form.image_path.length }} 张文档图片</span>
                    </div>
                    <div class="image-grid">
                      <div v-for="(image, index) in form.image_path" :key="index" class="image-card">
                        <div class="image-card-header">
                          <span class="image-number">第 {{ index + 1 }} 张文档</span>
                          <span v-if="image && image.startsWith('data:image/tiff;base64,')" class="tiff-badge">TIFF</span>
                        </div>
                        <div class="image-card-body">
                          <img :src="image && image.startsWith('data:image/tiff;base64,') ? displayTiffImage(image) : image" 
                               class="document-image" :alt="`文档图片 ${index + 1}`" @click="openImageViewer(image)">
                          <div v-if="image && image.startsWith('data:image/tiff;base64,')" class="tiff-controls">
                            <el-button type="primary" size="mini" @click="downloadTiffImage(image, `文档${index + 1}.tif`)">
                              下载TIFF文件
                            </el-button>
                          </div>
                        </div>
                        <div class="image-card-footer">
                          <el-button type="text" size="small" icon="el-icon-zoom-in" @click="openImageViewer(image)">放大查看</el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else class="no-image">
                    <i class="el-icon-document"></i>
                    <p>暂无文档图片</p>
                  </div>
                </div>
              </div>
              
              <div v-if="activeName == '公章识别'" class="seal-recognition-container">
                <div class="seal-info-card">
                  <div class="card-header">
                    <i class="el-icon-stamp"></i>
                    <span>公章信息</span>
                  </div>
                  <div class="card-body">
                    <div class="info-item">
                      <div class="info-label">公章名称：</div>
                      <div class="info-value">
                        <el-input v-model="form.gzmc.value" size="small" placeholder="请输入公章名称" />
                      </div>
                    </div>
                    <div class="info-item">
                      <div class="info-label">公章编号：</div>
                      <div class="info-value">
                        <el-input v-model="form.gzbh.value" size="small" placeholder="请输入公章编号" />
                      </div>
                    </div>
                    <div class="info-item">
                      <div class="info-label">公章用途：</div>
                      <div class="info-value">
                        <el-input v-model="form.gzyt.value" size="small" placeholder="请输入公章用途" />
                      </div>
                    </div>
                 
                  </div>
                </div>
                
                <div class="seal-image-container">
                  <div class="card-header">
                    <i class="el-icon-picture"></i>
                    <span>公章识别结果</span>
                  </div>
                  <div class="seal-image-wrapper">
                    <div v-if="form.gzmc.value" class="seal-image">
                      <img :src="form.output_file" alt="公章识别图" class="seal-marked-image">
                      <div class="image-footer">
                        <i class="el-icon-info-circle"></i>
                        系统已自动在图像上标注公章位置
                      </div>
                    </div>
                    <div v-else class="no-seal-image">
                      <i class="el-icon-warning-outline"></i>
                      <p>暂无公章识别图像</p>
                    </div>
                  </div>
                </div>
              </div>

              <div v-if="activeName == '表单识别'">
                <div class="table-recognition-container">
                  <div v-if="form.mdArr && Object.keys(form.mdArr).length > 0">
                    <div v-for="(tableContent, tableKey, index) in form.mdArr" :key="tableKey" class="table-section" v-if="isTableContentValid(tableContent)">
                      <div class="table-header">
                        <i class="el-icon-document-copy"></i>
                        <span>表格 {{ getValidTableIndex(tableKey) }}</span>
                      </div>
                      <div class="markdown-content" v-html="convertMarkdownToHtml(tableContent)"></div>
                    </div>
                    <div v-if="Object.keys(form.mdArr).filter(key => isTableContentValid(form.mdArr[key])).length === 0" class="no-table-data">
                      <i class="el-icon-document"></i>
                      <p>没有有效的表格数据</p>
                    </div>
                  </div>
                  <div v-else class="no-table-data">
                    <i class="el-icon-document"></i>
                    <p>暂无表单识别数据</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>


    


    <el-dialog title="图片查看" :visible.sync="imageViewerVisible" width="80%" class="custom-dialog image-viewer-dialog">
      <div class="image-viewer">
        <img :src="currentImage" alt="图片">
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeImageViewer">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { artApi } from "@/api/art";
import { autoApi } from "@/api/auto";

import vkbeautify from "vkbeautify";

export default {
  components: {},
  data() {
    return {
      loading: false,
      jiaozhunstatus: false,
      data: null,
      z_status: "",
      codeText: "",
      key: "",
      link: "",
      list: [],
      dh: "",
      ztc: "",
      mj: "",
      bgqx: "",
      qzh: "",
      flh: "",
      gjc: "",
      lbh: "",
      wz: "",
      ajh: "",
      jh: "",
      sj: "1",
      tm: "",
      wjbh: "",
      ztlx: "",
      ztsl: "",
      ztdw: "",
      ztgg: "",
      zrz: "",
      swh: "",
      zy: "",
      dagdh: "",
      sjlx: "",
      fz: "",
      dialogVisible: false,
      dialogVisiblewbjz: false,
      activeName: "文档",
      saveStatus: false,
      batch_code: "",
      htmlContent: "",
      title: "",
      content: "",
      imageViewerVisible: false,
      currentImage: "",

      isDisabled: false,

      form: {
        id: "",
        image_path: [],
        dh: { value: "", guizeId: "" },
        ztc: { value: "", guizeId: "" },
        mj: { value: "", guizeId: "" },
        bgqx: { value: "", guizeId: "" },
        qzh: { value: "", guizeId: "" },
        flh: { value: "", guizeId: "" },
        gjc: { value: "", guizeId: "" },
        lbh: { value: "", guizeId: "" },
        wz: { value: "", guizeId: "" },
        jh: { value: "", guizeId: "" },
        ajh: { value: "", guizeId: "" },
        sj: { value: "", guizeId: "" },
        tm: { value: "", guizeId: "" },
        wjbh: { value: "", guizeId: "" },
        ztlx: { value: "纸张", guizeId: "" },
        ztsl: { value: "", guizeId: "" },
        ztdw: { value: "张", guizeId: "" },
        ztgg: { value: "A4", guizeId: "" },
        zrz: { value: "", guizeId: "" },
        swh: { value: "", guizeId: "" },
        zy: { value: "", guizeId: "" },
        dagdh: { value: "", guizeId: "" },
        sjlx: { value: "GCDA", guizeId: "" },
        fz: { value: "", guizeId: "" },
        gzmc: { value: "", guizeId: "" },
        gzbh: { value: "", guizeId: "" },
        gzyt: { value: "", guizeId: "" },
        article_id: "",
        content: "",
        contentzrdhh: "",
        text: "",
        textOs: "",
        output_file: "",
        md: "",
        mdArr: null,
      },
      rules: {
        template_name: [
          { required: true, message: "请输入模板名字", trigger: "blur" },
        ],
        priority: [
          { required: true, message: "请输入优先级", trigger: "blur" },
        ],
      },
    };
  },

  computed: {
    // 这是一个计算属性的 getter
    linkValue() {
      return (
        "/indexingSystem/save?article_id=" + this.form.id + "&key=" + this.key
      );
    },
  },
  async mounted() {
    this.form.id = this.$route.query.id;

    if (this.form.id != null) {
      await this.getDetail();

      if (this.audit_status == 0) {
        if (!this.form.ztc.value) {
          this.getText("ztc");
        }

        if (!this.form.mj.value) {
          this.getText("mj");
        }

        if (!this.form.gjc.value) {
          this.getText("gjc");
        }
        if (!this.form.wz.value) {
          this.getText("wz");
        }

        if (!this.form.sj.value) {
          this.getText("sj");
        }

        if (!this.form.tm.value) {
          this.getText("tm");
        }
        if (!this.form.wjbh.value) {
          this.getText("wjbh");
        }
        if (!this.form.zrz.value) {
          this.getText("zrz");
        }
        if (!this.form.swh.value) {
          this.getText("swh");
        }
        if (!this.form.dagdh.value) {
          this.getText("dagdh");
        }
        if (!this.form.fz.value) {
          this.getText("fz");
        }
      }
    } else {
      await this.getDetail();
    }
  },
  methods: {
    textxiaozhun() {
      this.dialogVisiblewbjz = true
    },

    getOutputFileUrl(outputFile) {
      // 如果路径已经是完整URL，直接返回
      if (outputFile.startsWith('http')) {
        return outputFile;
      }
      // 否则，添加服务器基础URL（假设服务器基础URL是http://127.0.0.1:8080）
      return `http://127.0.0.1:8080${outputFile}`;
    },

    openImageViewer(image) {
      // 检查是否是TIFF格式
      if (image && image.startsWith('data:image/tiff;base64,')) {
        // 创建一个下载按钮，添加到图片查看器
        this.$nextTick(() => {
          const viewerFooter = document.querySelector('.image-viewer-dialog .dialog-footer');
          if (viewerFooter && !viewerFooter.querySelector('.download-tiff-btn')) {
            const downloadBtn = document.createElement('button');
            downloadBtn.className = 'el-button el-button--primary download-tiff-btn';
            downloadBtn.innerHTML = '下载原始TIFF文件';
            downloadBtn.onclick = () => this.downloadTiffImage(image);
            viewerFooter.insertBefore(downloadBtn, viewerFooter.firstChild);
          }
        });
        
        // 显示提示图像
        this.currentImage = this.displayTiffImage(image);
      } else {
        // 非TIFF图像，直接显示
        this.currentImage = image;
      }
      
      this.imageViewerVisible = true;
    },

    closeImageViewer() {
      this.imageViewerVisible = false;
    },

    async jiaozhunbuttombaocun() {
      const url = "jiaozhunbuttomBaocun";
      var res = await artApi(url, { id: this.form.id, "content": this.form.text });
      if (res.code == 200) {
        this.$message.success("保存成功！");
        window.location.href = "/dashboard/save?id=" + this.form.id;
      }
    },

    async jiaozhunbuttom() {
      this.jiaozhunstatus = true;
      const url = "xiaozhun";
      var res = await artApi(url, { id: this.form.id });
      if (res.code == 200) {
        this.$message.success("校对成功");
        this.form.text = res.data;
        this.jiaozhunstatus = false;
      }
    },

    handleInputChange(type) {
      let data = this.form[type].value;

      this.form[type].guizeId = "";

      for (var i = 0; i < this[type].length; i++) {
        if (this[type][i].value == data) {
          this.form[type].guizeId = this[type][i].guizheId;

          return true;
        }
      }

      console.log(this.form[type]);
    },

    xuanzhe(objct) {
      console.log(objct.key);
      this.form[objct.key]["value"] = objct.value;
      this.form[objct.key]["guizeId"] = objct.guizheId;

      this.dialogVisible = false;
    },
    async getText(field) {
      const url = "getTextByField";
      var res = await artApi(url, { id: this.form.id, name: field });
      if (res.code == 200) {
        let data = res.data;
        if (data.length > 0) {
          this.form[field]["value"] = data[0].value;
          this.form[field]["guizeId"] = data[0].guizheId;
          this[field] = data;
        }
      }
    },

    biaoyinskip(key) {
      this.list = this[key];
      this.dialogVisible = true;
      this.key = key;
      // this.$router.push('/indexingSystem/save?key=' + key + '&article_id=' + this.form.id)
    },

    async autobiaoyin() {
      const url = "autobiaoyin";
      var res = await artApi(url, { id: this.form.id });
      if (res.code == 200) {
        console.log(1)
      }
    },

    async getDetail() {
      // this.loading = true;
      const url = "getArticleByidabutBiaoyinAuto";
      var res = await autoApi(url, { id: this.form.id });
      if (res.code == 200) {

        if (res.data == "") {


          // alert()
          this.$confirm('档案全部审核完成，跳转到档案列表', '提示', {
            showCancelButton: false,
            type: 'success'
          }).then(() => {
            // 用户点击确定后的逻辑
            window.location.href = "/documentfilemana/index";
          })

          return "1";
        }



        this.form.dh.value = res.data.dh;
        this.form.ztc.value = res.data.ztc;
        this.form.mj.value = res.data.mj;
        this.form.bgqx.value = res.data.bgqx;
        this.form.flh.value = res.data.flh;
        this.form.ajh.value = res.data.ajh;
        this.form.qzh.value = res.data.qzh;
        this.form.jh.value = res.data.jh;
        this.form.gjc.value = res.data.gjc;
        this.form.lbh.value = res.data.lbh;
        this.form.wz.value = res.data.wz;
        this.form.sj.value = res.data.sj;
        this.form.tm.value = res.data.tm;
        this.form.wjbh.value = res.data.wjbh;
        this.form.ztlx.value = res.data.ztlx;
        this.form.ztsl.value = res.data.ztsl;
        this.form.ztdw.value = res.data.ztdw;
        this.form.ztgg.value = res.data.ztgg;
        this.form.zrz.value = res.data.zrz;
        this.form.swh.value = res.data.swh;
        this.form.gzmc.value = res.data.gzmc;
        this.form.gzbh.value = res.data.gzbh;
        this.form.gzyt.value = res.data.gzyt;
        this.form.output_file = res.data.output_file;
        this.form.mdArr = res.data.mdArr;



        this.form.id = res.data.id;
        this.form.image_path = res.data.image_path;
        this.form.doubpdf_url = res.data.doubpdf_url;



        this.form.content = res.data.content;
        this.form.text = res.data.text;
        this.form.textOs = res.data.text;

        this.form.ztsl.value = res.data.ztsl;
        this.form.contentzrdhh = res.data.contentzrdhh;
        this.z_status = res.data.z_status;
        this.codeText = vkbeautify.xml(res.data.xml);
        this.data = res.data;

        this.form.gzmc.value = res.data.gzmc || '';
        this.form.gzbh.value = res.data.gzbh || '';
        this.form.gzyt.value = res.data.gzyt || '';
        this.form.output_file = res.data.output_file || '';
      }
      this.loading = false;
    },

    submit(type) {
      this.$refs.dataForm.validate(async (valid) => {
        if (valid) {
          // this.isDisabled = true
          let params = this.form;
          const url = "uptDocument";
          let postData =  this.form;
          postData.image_path=[]
          var res = await autoApi(url, postData);
          if (res.code == 200) {
            this.$message.success("操作成功！");

            if (type == 1) {
              window.location.href = "/dashboard/indexreview?id=" + res.data;
            }
            if (type == 2) {
              this.$router.push("/documentfilemana/index");
            }
          } else {
            this.$message.error(res.msg);
          }
          this.isDisabled = false;
        }
      });
    },

    getJsonValue(jsonString, key) {
      try {
        if (!jsonString) return null;
        const parsed = typeof jsonString === 'string' ? JSON.parse(jsonString) : jsonString;
        return parsed[key] || null;
      } catch (error) {
        console.error('JSON解析错误:', error);
        return null;
      }
    },

    convertMarkdownToHtml(markdown) {
      if (!markdown) return '';
      
      // 预处理markdown内容，修复数据错位
      markdown = this.preprocessTableData(markdown);
      
      let html = '';
      const lines = markdown.split('\n');
      
      // 查找表头行和分隔行
      let headerRow = -1;
      let separatorRow = -1;
      
      for (let i = 0; i < lines.length; i++) {
        if (lines[i].trim().startsWith('|') && lines[i].trim().endsWith('|')) {
          if (headerRow === -1) {
            headerRow = i;
          } else if (separatorRow === -1 && lines[i].includes('---')) {
            separatorRow = i;
            break;
          }
        }
      }
      
      // 如果找到表头和分隔行，则开始处理表格
      if (headerRow !== -1 && separatorRow !== -1) {
        html += '<table class="md-table">';
        
        // 处理表头
        let headerLine = lines[headerRow].trim();
        let headerCells = headerLine.substring(1, headerLine.length - 1).split('|');
        
        html += '<thead><tr>';
        headerCells.forEach(cell => {
          const cellText = cell.trim();
          // 添加title属性，这样当鼠标悬停时可以显示完整的表头文字
          html += `<th title="${cellText}">${cellText}</th>`;
        });
        html += '</tr></thead>';
        
        // 处理表格内容
        html += '<tbody>';
        for (let i = separatorRow + 1; i < lines.length; i++) {
          const line = lines[i].trim();
          if (line.startsWith('|') && line.endsWith('|')) {
            // 去掉开头和结尾的 | 符号，然后按 | 分割
            let rowContent = line.substring(1, line.length - 1);
            let cells = rowContent.split('|');
            
            // 确保单元格数量与表头一致
            while (cells.length < headerCells.length) {
              cells.push(''); // 如果单元格不足，添加空单元格
            }
            
            html += '<tr>';
            cells.forEach((cell, index) => {
              if (index < headerCells.length) { // 确保不超过表头列数
                const cellText = cell.trim();
                // 为单元格也添加title属性，以便查看完整内容
                html += `<td title="${cellText}">${cellText}</td>`;
              }
            });
            html += '</tr>';
          }
        }
        html += '</tbody></table>';
      } else {
        // 简单的文本转换
        html = markdown.replace(/\n/g, '<br>');
      }
      
      return html;
    },
    
    // 预处理表格数据，修复可能的数据错位问题
    preprocessTableData(markdown) {
      if (!markdown) return '';
      
      const lines = markdown.split('\n');
      let headerRow = -1;
      let separatorRow = -1;
      
      // 查找表头和分隔行
      for (let i = 0; i < lines.length; i++) {
        if (lines[i].trim().startsWith('|') && lines[i].trim().endsWith('|')) {
          if (headerRow === -1) {
            headerRow = i;
          } else if (separatorRow === -1 && lines[i].includes('---')) {
            separatorRow = i;
            break;
          }
        }
      }
      
      if (headerRow === -1 || separatorRow === -1) return markdown;
      
      // 获取表头
      const headerLine = lines[headerRow].trim();
      const headers = headerLine.substring(1, headerLine.length - 1).split('|').map(h => h.trim());
      
      // 找到年龄列和职务列的索引
      const ageIndex = headers.findIndex(h => h === '年龄');
      const positionIndex = headers.findIndex(h => h === '职务');
      
      // 如果找不到这两列，则返回原始数据
      if (ageIndex === -1 || positionIndex === -1) return markdown;
      
      // 处理数据行
      const resultLines = [];
      resultLines.push(...lines.slice(0, separatorRow + 1));
      
      for (let i = separatorRow + 1; i < lines.length; i++) {
        const line = lines[i].trim();
        if (line.startsWith('|') && line.endsWith('|')) {
          const rowContent = line.substring(1, line.length - 1);
          const cells = rowContent.split('|').map(c => c.trim());
          
          // 检查年龄列是否包含非数字内容，如"项目付经理"
          if (cells.length > ageIndex && cells.length > positionIndex) {
            const ageValue = cells[ageIndex];
            const positionValue = cells[positionIndex];
            
            // 如果年龄列包含"项目"或"经理"等词，且不是纯数字，可能是错位的
            if (ageValue && (/项目|经理|总工|主任/.test(ageValue)) && !/^\d+$/.test(ageValue)) {
              // 交换年龄列和职务列的值
              const temp = cells[ageIndex];
              cells[ageIndex] = cells[positionIndex];
              cells[positionIndex] = temp;
            }
          }
          
          // 重建行
          let newLine = '|';
          cells.forEach(cell => {
            newLine += ` ${cell} |`;
          });
          resultLines.push(newLine);
        } else {
          resultLines.push(line);
        }
      }
      
      return resultLines.join('\n');
    },

    // 转换base64编码的TIFF为可显示格式
    displayTiffImage(tiffBase64Data) {
      // 如果不是TIFF格式，直接返回原始数据
      if (!tiffBase64Data || !tiffBase64Data.startsWith('data:image/tiff;base64,')) {
        return tiffBase64Data;
      }
      
      // 为TIFF图像创建占位图
      return '';
    },
    
    // 创建并下载TIFF文件
    downloadTiffImage(tiffBase64Data, filename = 'document.tif') {
      if (!tiffBase64Data || !tiffBase64Data.startsWith('data:image/tiff;base64,')) {
        this.$message.warning('不是有效的TIFF图像数据');
        return;
      }
      
      // 创建下载链接
      const downloadLink = document.createElement('a');
      downloadLink.href = tiffBase64Data;
      downloadLink.download = filename;
      
      // 触发下载
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    },

    isTableContentValid(tableContent) {
      if (!tableContent || tableContent.trim() === '') {
        return false;
      }
      
      // 检查是否只有表头而没有实际数据
      const lines = tableContent.split('\n');
      let headerRow = -1;
      let separatorRow = -1;
      let hasDataRows = false;
      
      // 查找表头、分隔行和数据行
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        if (line.startsWith('|') && line.endsWith('|')) {
          if (headerRow === -1) {
            headerRow = i;
          } else if (separatorRow === -1 && line.includes('---')) {
            separatorRow = i;
          } else if (separatorRow !== -1) {
            // 如果找到了分隔行之后的数据行
            hasDataRows = true;
            break;
          }
        }
      }
      
      // 只有当表格有表头、分隔行和至少一行数据时才显示
      return headerRow !== -1 && separatorRow !== -1 && hasDataRows;
    },
    
    getValidTableIndex(currentKey) {
      // 获取所有有效表格的键
      const validTableKeys = Object.keys(this.form.mdArr).filter(key => this.isTableContentValid(this.form.mdArr[key]));
      // 找到当前键在有效表格键列表中的索引位置
      const indexInValidTables = validTableKeys.indexOf(currentKey);
      // 返回索引+1作为表格编号
      return indexInValidTables + 1;
    },

  },
};
</script>

<style scoped>
::v-deep .el-tabs__header {
  padding: 0;
  position: relative;
  margin: 0 0 0 0;
}

::v-deep .el-form-item {
  margin-bottom: 12px;
}

::v-deep .el-button--mini {
  height: 28px;
  line-height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 整体页面样式 */
.app-container {
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-container {
  position: relative;
  width: 100%;
}

/* 页面头部样式 */
.page-header-wrapper {
  width: 100%;
  margin-bottom: 20px;
}

.header-status-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.status-indicator {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 4px;
}

.status-pending {
  background-color: #fff8f6;
}

.status-pending i {
  font-size: 22px;
  color: #f56c6c;
}

.status-pending span {
  color: #f56c6c;
  font-weight: bold;
  margin-left: 8px;
}

.status-approved {
  background-color: #f0f9eb;
}

.status-approved i {
  font-size: 22px;
  color: #67c23a;
}

.status-approved span {
  color: #67c23a;
  font-weight: bold;
  margin-left: 8px;
}

.status-description {
  color: #909399;
  font-size: 12px;
  margin-left: 15px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

/* 主内容区域样式 */
.main-content-wrapper {
  display: flex;
  width: 100%;
  gap: 20px;
  margin-top: 10px;
}

/* 表单区域样式 */
.form-section {
  flex: 3;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 5px;
}

.form-item {
  flex: 1;
}

/* 内容显示区域样式 */
.content-section {
  flex: 2;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.content-tabs-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.tab-content-wrapper {
  padding: 15px 5px;
  flex: 1;
  overflow: auto;
}

.custom-tabs ::v-deep .el-tabs__item {
  height: 32px;
  line-height: 32px;
  font-size: 13px;
  color: #606266;
}

.custom-tabs ::v-deep .el-tabs__item.is-active {
  color: #409EFF;
  font-weight: bold;
}

.custom-tabs ::v-deep .el-tabs__active-bar {
  height: 3px;
  background-color: #409EFF;
}

.text-content {
  width: 100%;
  height: auto;
  overflow: auto;
  white-space: pre-wrap;
  font-size: 12px;
  line-height: 1.6;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}

.pending-notice {
  margin-top: 15px;
  padding: 10px;
  background-color: #fff8f6;
  border-radius: 4px;
  color: #f56c6c;
}

/* 弹窗样式 */
.custom-dialog ::v-deep .el-dialog__header {
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.custom-dialog ::v-deep .el-dialog__title {
  font-size: 16px;
  color: #303133;
  font-weight: bold;
}

.custom-dialog ::v-deep .el-dialog__body {
  padding: 20px;
}

.custom-dialog ::v-deep .el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
}

.dialog-content {
  max-height: 400px;
  overflow: auto;
}

.options-list {
  margin-bottom: 15px;
}

.option-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  margin-bottom: 8px;
  border-radius: 4px;
  background-color: #f5f7fa;
  transition: all 0.3s;
}

.option-item:hover {
  background-color: #ecf5ff;
}

.option-text {
  flex: 1;
  padding-right: 10px;
  word-break: break-all;
}

.option-button {
  flex-shrink: 0;
}

.dialog-footer-links {
  margin-top: 20px;
  text-align: center;
}

/* 文本校准弹窗样式 */
.text-calibration-container {
  display: flex;
  gap: 20px;
}

.original-text {
  width: 48%;
  height: auto;
  overflow: auto;
  white-space: pre-wrap;
  font-size: 12px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}

.edited-text {
  width: 48%;
}

.calibration-textarea ::v-deep .el-textarea__inner {
  font-size: 12px;
  font-family: monospace;
}

/* 文档图片查看器样式已保留 */
.document-image-viewer {
  width: 100%;
  padding: 10px 0;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.image-container {
  position: relative;
  width: 100%;
  padding: 10px;
}

.image-grid {
  display: flex;
  flex-direction: column;
  gap: 30px;
  padding: 15px 0;
}

.image-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.image-card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-5px);
}

.image-card-header {
  padding: 12px 15px;
  background-color: #409EFF;
  color: white;
  font-weight: bold;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.image-card-body {
  padding: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
  min-height: 200px;
}

.image-card-footer {
  padding: 10px 15px;
  border-top: 1px solid #ebeef5;
  text-align: right;
  background-color: #fff;
}

.image-number {
  display: flex;
  align-items: center;
}

.image-number::before {
  content: "";
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: #fff;
  border-radius: 50%;
  margin-right: 8px;
}

.document-image {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.document-image:hover {
  transform: scale(1.01);
}

.image-navigation {
  text-align: center;
  margin-bottom: 20px;
  color: #606266;
  font-size: 15px;
  background-color: #ecf5ff;
  padding: 15px;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.image-navigation i {
  font-size: 20px;
  margin-right: 8px;
  color: #409EFF;
}

.no-image {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  color: #909399;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.no-image i {
  font-size: 64px;
  margin-bottom: 15px;
  color: #DCDFE6;
}

.no-image p {
  font-size: 16px;
}

.image-viewer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
}

.image-viewer img {
  max-width: 100%;
  max-height: 70vh;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}

.image-viewer-dialog ::v-deep .el-dialog {
  max-width: 90%;
}

/* 过滤容器分隔线 */
.filter-container::after {
  content: none;
}

.always-underlined {
  text-decoration: underline;
}

.seal-recognition-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.seal-info-card {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
  border-radius: 8px 8px 0 0;
}

.card-body {
  padding: 20px;
}

.card-header i {
  font-size: 20px;
  margin-right: 8px;
  color: #409EFF;
}

.card-header span {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.info-item {
  display: flex;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #ebeef5;
}

.info-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.info-label {
  width: 100px;
  font-size: 14px;
  color: #606266;
  font-weight: bold;
}

.info-value {
  flex: 1;
  font-size: 14px;
  color: #303133;
}

.seal-image-container {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.seal-image-wrapper {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.seal-image {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.seal-marked-image {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.image-footer {
  margin-top: 15px;
  padding: 8px 15px;
  background-color: #ecf5ff;
  color: #409EFF;
  border-radius: 4px;
  font-size: 13px;
}

.no-seal-image {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  width: 100%;
  color: #909399;
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px dashed #dcdfe6;
}

.no-seal-image i {
  font-size: 64px;
  margin-bottom: 15px;
  color: #DCDFE6;
}

.no-seal-image p {
  font-size: 16px;
}

.info-actions {
  margin-top: 20px;
  text-align: right;
}

.table-recognition-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.table-section {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 25px;
  overflow: hidden;
}

.table-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
  border-radius: 8px 8px 0 0;
}

.table-header i {
  font-size: 20px;
  margin-right: 8px;
  color: #409EFF;
}

.table-header span {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.markdown-content {
  padding: 0;
  white-space: pre-wrap;
  font-size: 14px;
  line-height: 1.6;
  overflow-x: auto; /* 允许水平滚动 */
}

.markdown-content .md-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 0;
  font-size: 14px;
  border: 1px solid #ebeef5;
  table-layout: auto; /* 改为自动布局，让浏览器根据内容自动调整列宽 */
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  min-width: 800px; /* 设置最小宽度，确保表格不会过小 */
}

.markdown-content .md-table tr {
  border-bottom: 1px solid #ebeef5;
  height: 48px; /* 固定行高 */
}

.markdown-content .md-table tr:last-child {
  border-bottom: none;
}

.markdown-content .md-table tr:nth-child(even) {
  background-color: #fafafa;
}

.markdown-content .md-table tr:hover {
  background-color: #f0f7ff;
}

.markdown-content .md-table th,
.markdown-content .md-table td {
  padding: 12px 8px;
  text-align: center; /* 居中对齐 */
  border: 1px solid #ebeef5;
  word-break: break-word; /* 允许在单词内换行 */
  min-width: 80px; /* 设置最小列宽 */
  max-width: 200px; /* 设置最大列宽 */
  overflow: hidden;
  text-overflow: ellipsis; /* 超出显示省略号 */
  white-space: nowrap; /* 防止换行 */
  vertical-align: middle; /* 垂直居中 */
}

.markdown-content .md-table th {
  position: sticky; /* 固定表头 */
  top: 0; /* 固定在顶部 */
  background-color: #f0f6fc;
  z-index: 10; /* 确保表头在内容之上 */
  font-weight: bold;
  white-space: nowrap; /* 表头不换行 */
  overflow: hidden;
  text-overflow: ellipsis; /* 超出显示省略号 */
}

.markdown-content .md-table th:hover::after {
  content: attr(title); /* 悬停时显示完整表头文字 */
  position: absolute;
  left: 0;
  top: 100%;
  background: #303133;
  color: white;
  padding: 5px 8px;
  border-radius: 4px;
  z-index: 20;
  white-space: normal;
  max-width: 200px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  pointer-events: none;
}

.markdown-content .md-table thead tr {
  background-color: #f0f6fc;
  color: #303133;
  height: 52px; /* 表头行高稍大 */
}

.markdown-content .md-table thead th {
  border-bottom: 2px solid #409eff;
  text-transform: none;
  letter-spacing: 0.5px;
}

/* 滚动条样式美化 */
.markdown-content::-webkit-scrollbar {
  height: 8px;
}

.markdown-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.markdown-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.markdown-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式处理 */
@media screen and (max-width: 768px) {
  .markdown-content .md-table {
    font-size: 12px;
    min-width: 650px;
  }

  .markdown-content .md-table th,
  .markdown-content .md-table td {
    padding: 8px 4px;
    min-width: 60px;
  }
}

.no-table-data {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  color: #909399;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.no-table-data i {
  font-size: 64px;
  margin-bottom: 15px;
  color: #DCDFE6;
}

.no-table-data p {
  font-size: 16px;
}

.tiff-badge {
  background-color: #409EFF;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
}

.tiff-controls {
  position: absolute;
  bottom: 10px;
  right: 10px;
  z-index: 10;
}

.image-card-body {
  position: relative;
}
</style>
